require 'digest/sha1'

# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.

class ApplicationController < ActionController::Base
  helper :all # include all helpers, all the time
  include ApplicationHelper

  # See ActionController::RequestForgeryProtection for details
  # Uncomment the :secret if you're not using the cookie session store
#  protect_from_forgery :secret => 'fb468dccf7283118bfbbcd0705c767b8'
  protect_from_forgery :only => [:create, :update, :destroy] 

  include RelativePath

  # Pick a unique cookie name to distinguish our session data from others'
  session :session_key => '_wiki-on-rails_session_id'
  init_gettext "wiki"

  #
  # $B%A%c%l%s%8(B&$B%l%9%]%s%9MQ$N%A%c%l%s%8%3!<%I$r@8@.$9$k(B
  #
  def _create_challenge_code
    session['challenge'] = Digest::SHA1.hexdigest(rand.to_s)
  end

  #
  # $BJ];}$7$F$*$$$?%A%c%l%s%8(B&$B%l%9%]%s%9MQ$N%A%c%l%s%8%3!<%I$r<hF@$9$k(B
  # nil$B$N>l9g$O@8@.$9$k(B
  #
  def _get_challenge_code
    session['challenge'] || _create_challenge_code
  end

  #
  # $BJ];}$7$F$*$$$?%A%c%l%s%8(B&$B%l%9%]%s%9MQ$N%A%c%l%s%8%3!<%I%@%$%8%'%9%H$r<hF@$9$k(B
  #
  def _get_challenge_code_digest
    Digest::SHA1.hexdigest(_get_challenge_code.to_s + ADMIN_PASS)
  end

  #
  # $B%l%9%]%s%9%3!<%I$r>H9g$9$k(B
  #
  # @param  string response $B%V%i%&%6$+$iJV$5$l$?%l%9%]%s%9%3!<%I(B
  # @return bool   true:OK false:NG
  #
  def _check_challenge_code response
    response == _get_challenge_code_digest
  end
end
